package generic;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class GenericServer {

	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		ServerSocket listen = null;
		Class<? extends ConnectionHandler> handlerClass = null;
		int port = 0;
		if(args.length < 2)
		{
			System.out.println("Please supply a port (1-(2^16-1)) and handler class name as parameters.");
			return;
		}
		
		if(System.getenv().containsKey("READINGS_PORT")){
			port = Integer.parseInt(System.getenv().get("READINGS_PORT"));
		}
		else
			port = Integer.parseInt(args[0]);
		
		try {
			handlerClass = (Class<? extends ConnectionHandler>) Class.forName(args[1]);
			listen = new ServerSocket(port);
		} catch (NumberFormatException e) {
			System.out.println(args[0] + " is not a valid port number.");
		} catch (ClassNotFoundException e) {
			System.out.println(args[1] + " is not a valid handler class: " + e.getMessage());
		} catch (IOException e) {
			System.out.println("Could not open listener: " + e.getMessage());
		}
		try {
			while(true)
			{
				Socket incoming = listen.accept();
				ConnectionHandler handler =  handlerClass.newInstance();
				handler.setSocket(incoming);
				handler.start();
			}
		} catch (IOException e) {
			System.out.println("IOException when accepting new incoming connection: " + e.getMessage());
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
